import { routerRedux } from 'dva/router';
import * as helpService from '../services/helpService';
import { Toast } from 'antd-mobile';

export default {
  namespace: 'help',
  state: {
    list: [],
    content: {},
    recommend: [],
    loading: false,
  },
  reducers: {
    save(state, { payload }) {
      return { ...state, ...payload };
    },
  },
  effects: {
    *fetch({ payload }, { put, call, select }) {
      const list = yield select(state => state.help.list);
      if (!list.length) {
        const { data } = yield call(helpService.fetch);
        yield put({
          type: 'save',
          payload: {
            list: data,
          },
        });
      }
    },
    *content({ payload }, { put, call, select }) {
      const { data } = yield call(helpService.content, payload.id);
      yield put({
        type: 'save',
        payload: {
          content: data,
        },
      });
    },
    *search({ payload }, { put, call, select }) {
      const { data } = yield call(helpService.fetch, payload.key);
      yield put({
        type: 'save',
        payload: {
          recommend: data,
        },
      });
    },
    *feedback({ payload }, { put, call, select }) {
      yield put({ type: 'save', payload: { loading: true } });
      const { data } = yield call(helpService.feedback, payload);
      yield put({ type: 'save', payload: { loading: false } });
      if (data && data.ok) {
        setTimeout(() => {
          Toast.success('提交成功，感谢您的意见', 1);
        }, 50);
        yield new Promise((resolve) => {
          setTimeout(() => { resolve(); }, 1050);
        });
        yield put(routerRedux.push('/help'));
      } else {
        setTimeout(() => {
          Toast.fail('提交失败，请重试', 1);
        }, 50);
      }
    },
  },
  subscriptions: {
    setup({ dispatch, history }) {
      history.listen((location) => {
        if (location.pathname === '/help') {
          dispatch({ type: 'fetch' });
        } else if (location.pathname === '/helpContent') {
          dispatch({ type: 'content', payload: { id: location.query.id } });
        }
      });
    },
  },
};
